package model;

import java.awt.Point;
import java.awt.geom.Line2D;

/**
 * A class that contains a series of static math related functions that are used
 * throughout the model.
 * 
 * @author Andrew Patterson
 */
public class LogoMath
{    
    /**
     * Calculates the determinant of a 2x2 matrix of the form [[a.b],[c,d]]
     */
    public static double det(double a, double b, double c, double d)
    {
        return a * d - b * c;
    }
    
    
    /**
     * Calculates the distance between two points Point a and Point b
     */
    public static double distanceFormula(Point a, Point b)
    {
        return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
    }
    
    
    /**
     * Calculates and returns an intersection point between two lines based on matrix determinants
     * Returns an empty point the lines do not intersect
     * 
     * @author With help from Wolfram MathWorld
     */
    public static Point calculateIntersection(Line2D turtlePath, Line2D currentBoundary)
    {
        Point intersectionPoint = new Point();
        intersectionPoint.x = (int) (det(det(turtlePath.getX1(), turtlePath.getY1(), turtlePath.getX2(), turtlePath.getY2()), turtlePath.getX1() - turtlePath.getX2(),
                             det(currentBoundary.getX1(), currentBoundary.getY1(), currentBoundary.getX2(), currentBoundary.getY2()), currentBoundary.getX1() - currentBoundary.getX2())/
                         det(turtlePath.getX1() - turtlePath.getX2(), turtlePath.getY1() - turtlePath.getY2(), currentBoundary.getX1() - currentBoundary.getX2(), currentBoundary.getY1() - currentBoundary.getY2()));
        intersectionPoint.y = (int) (det(det(turtlePath.getX1(), turtlePath.getY1(), turtlePath.getX2(), turtlePath.getY2()), turtlePath.getY1() - turtlePath.getY2(),
                             det(currentBoundary.getX1(), currentBoundary.getY1(), currentBoundary.getX2(), currentBoundary.getY2()), currentBoundary.getY1() - currentBoundary.getY2())/
                         det(turtlePath.getX1() - turtlePath.getX2(), turtlePath.getY1() - turtlePath.getY2(), currentBoundary.getX1() - currentBoundary.getX2(), currentBoundary.getY1() - currentBoundary.getY2()));
        if(intersectionPoint.x == 0) intersectionPoint.x++;
        else intersectionPoint.x --;
        if(intersectionPoint.y == 0) intersectionPoint.y++;
        else intersectionPoint.y --;
        return intersectionPoint;       
    }
    
    
    /**
     * Maintains a degree range of >=0 and < 360
     * 
     * @param degrees
     * @return a simplified version of degrees
     */
    public static int simplifyAngle (int degrees)
    {
        while (degrees >= 360){
            degrees -= 360;
        }
        while (degrees < 0){
            degrees += 360;
        }
        return degrees;
    }

}
